package com.abcdefg.springtrans.controller;



import com.abcdefg.springtrans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.io.IOException;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    /**
     * JDBC事务管理器
     */
//    @Autowired
//    private DataSourceTransactionManager transactionManager;
    /**
     * 定义事务属性
     */
//    @Autowired
//    private TransactionDefinition transactionDefinition;
    @Autowired
    private UserService userService;
//    @Transactional(rollbackFor = Exception.class)
    @Transactional(isolation= Isolation.READ_COMMITTED)
    @RequestMapping("/registry")
    public String registry(String name,String password) throws IOException {
        //开启事务
//        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        //⽤⼾注册
        userService.registryUser(name,password);
        log.info("数据插入成功！");
        //提交事务
//        transactionManager.commit(status);
        //回滚事务
//        transactionManager.rollback(status);
//        try {
//            int a=10/0;
//        } catch (Exception e) {
//            //打印栈错误异常可以运行成功
//            e.printStackTrace();
//            //throw e 不能运行成功
////            throw e;
//            //手动提交事务，这里也可以运行成功
////            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }

        if(true){
            //这里虽然会抛出异常，但是不影响事务的提交
            throw new IOException();
        }
        return "注册成功";
    }
}
